package cn.cihon.ubi.qorosauto.util;

import java.util.ArrayList;;

/**
 * 用于统计某种行车指标的众数
 * @author guodawei
 */
public class ModeArrayList extends ArrayList<Double> {
	
	private static final long serialVersionUID = 1L;

	
	/**
	 * 统计集合内成员中的众数，如果众数存在多个，取值较小的数作为众数
	 * @return
	 * @throws Exception
	 */
	public Double getMode() throws Exception {

		if (this.size() == 0) {
			throw new Exception("没有行车数据，不能计算众数！");
		}
		
		if (!(this.get(0) instanceof Double)) {
			throw new Exception("非法数据类型，必须载入是Double类型行车数据才能计算众数！");
		}
		
	    Double mode = new Double(0);
	    int maxCount = 0;

	    for (int i = 0; i < this.size(); i++) {
	    	
	    	Double value = (Double)this.get(i);
	        int count = 0;
	        
	        if (mode.equals(value)) {
	        	continue;
	        }
	        
	        for (int j = 0; j < this.size(); j++) {	        	
	        	Double compareValue = (Double)this.get(j);
	            if (value.equals(compareValue)) {
	            	count ++;
	            }
	        }
	        
	        if (count > maxCount) {
	            maxCount = count;
	            mode = value;
	        }
	        
	        // 取较小值作为众数输出
	        if (count == maxCount) {
	        	if (value < mode) {
					mode = value;
				}
	        }
	    }

	    return mode;
	    
	}
	
}
